//
//  AppStateHandler.m
//  iengage
//
//  Created by Luis Ziliani on 2/24/09.
//  Copyright 2009 Manas. All rights reserved.
//

#import "AppStateHandler.h"

#define LastUserLatitudeKey		@"lastUserLatitude"
#define LastUserLongitudeKey	@"lastUserLongitude"
#define LastUserViewedKey		@"lastUserViewed"


@implementation AppStateHandler

@synthesize lastUserLatitude, lastUserLongitude, lastUserViewed;

- (NSString *) file {
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
														 NSUserDomainMask, YES); 
	NSMutableString *documentsDirectory = [[NSMutableString alloc] initWithString: [paths objectAtIndex:0]]; 
	[documentsDirectory appendString:@"/data"];
	[documentsDirectory autorelease];
	
	return documentsDirectory;	
}

- (void) restoreStateIfPossible {
	
	@try {
		NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:[self file]];
		NSNumber *longitude = [dic objectForKey:LastUserLongitudeKey];
		NSNumber *latitude = [dic objectForKey:LastUserLatitudeKey];
		NSString *user = [dic objectForKey:LastUserViewedKey];
		
		[self setLastUserLatitude: [latitude doubleValue]];
		[self setLastUserLongitude: [longitude doubleValue]];
		[self setLastUserViewed: user];
		[dic release];
	}
	@catch (NSException * e) {
		
	}
}

- (void) saveState {
	NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

	NSNumber *longitude = [NSNumber numberWithDouble: [self lastUserLongitude]];
	NSNumber *latitude = [NSNumber numberWithDouble: [self lastUserLatitude]];

	[dic setObject:longitude forKey:LastUserLongitudeKey];
	[dic setObject:latitude	 forKey:LastUserLatitudeKey];
	
	if (lastUserViewed == nil) {
		[dic setObject:@"" forKey:LastUserViewedKey];
	}
	else {
		[dic setObject:lastUserViewed forKey:LastUserViewedKey];
	}
	
	[dic writeToFile:[self file] atomically:NO];
	[dic release];
}

@end
